package com.wendy.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author zhuwending
 */
@Slf4j
public class FileUtil {

    public static String getFileNameOnly(MultipartFile file) {
        if (null == file) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        return fileName.substring(fileName.lastIndexOf("/") + 1, fileName.lastIndexOf("."));
    }

    public static String getFileSuffix(MultipartFile file) {
        if (null == file) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    private static boolean uploadFile(InputStream inputStream, String path, String fileName) {
        if (null == inputStream || StringUtils.isBlank(path)) {
            return false;
        }
        File file = new File(path);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                log.error("create directory error");
                return false;
            }
        }
        file = new File(path + File.separator + fileName);
        if (!file.exists()) {
            try {
                if (!file.createNewFile()) {
                    log.error("create file error");
                }
            } catch (IOException e) {
                log.error("create File error", e);
            }
        } else {
            log.error("file already exists");
            return false;
        }
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            int length;
            byte[] buffer = new byte[1024];
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            return true;
        } catch (IOException e) {
            log.error("IO stream error", e);
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                inputStream.close();
            } catch (IOException e) {
                log.error("close IO steam error", e);
            }
        }
        return false;
    }

    public static boolean uploadFile(MultipartFile file, String path, String fileName) throws IOException {
        return uploadFile(file.getInputStream(), path, fileName);
    }
}
